'use strict';
var cmdbFormly = angular.module('formlyCMDB', [
    'formly', 'formlyBootstrap', 'ui.bootstrap',
    'ngSanitize','ui.select','ui.grid']);
app.requires.push('formlyCMDB');


cmdbFormly.controller('cmdbListCtrl', ['$rootScope', '$scope', '$parse', '$injector', '$http','$q', '$state', '$stateParams', '$modal', '$timeout', '$interval', 'i18nService', 'SweetAlert', 'FileUploader', 'Restangular', 'UserRestangular', 'BpmRestangular', 'api_configure_form', 'api_configure_data', 'api_bpm_domain', 'api_bpm_data', 'api_user_data', 'api_cmdb',
    function ($rootScope, $scope, $parse, $injector, $http, $q, $state, $stateParams, $modal, $timeout, $interval, i18nService, SweetAlert, FileUploader, Restangular, UserRestangular, BpmRestangular, api_configure_form, api_configure_data, api_bpm_domain, api_bpm_data, api_user_data, api_cmdb) {
    
    $scope.langs=i18nService.getAllLangs();
  	$scope.lang = 'zh-cn';
  	i18nService.setCurrentLang($scope.lang);
  
    var vm = this;
    vm.options = {};
    vm.exampleTitle = ['expressionProperties','model property'];
    vm.fields=[];
    vm.model={};
    vm.model["loginUser"] = $rootScope.user;
    var that=$injector;
    var parse=$parse;

    var formKey = "";
    var pdKey = "";
    if(angular.isDefined($state.current.pdKey)&&$state.current.pdKey!=""){
        pdKey = $state.current.pdKey;
        //console.log("pdKey::"+$state.current.pdKey);
    }
    if(angular.isDefined($stateParams.formKey)&&$stateParams.formKey!=""){
        formKey = $stateParams.formKey;
        //console.log("formKey::"+$stateParams.formKey);
    }

    //用户测试数据，后续从header的auth中获取
    var userId = 2;
    userId = $rootScope.user.id;

    //==============处理表单设计数据  开始====================
    //处理组件加载后台数据选项的方法
    function refreshSelectOptions(searchVal, field) {
        if(field.templateOptions.optionsUrl){
            var process = BpmRestangular.all("");
            if(field.templateOptions.ApiService){
                process = UserRestangular.all("");
            }
            
            process.customPOST({"idx":0,"sum":1000},field.templateOptions.optionsUrl).then(function(result){
                if(!field.templateOptions.options){
                    field.templateOptions.options=[];
                }
                if(field.templateOptions.optionsDataKey){
                    field.templateOptions.options =result[field.templateOptions.optionsDataKey];
                }else{
                    field.templateOptions.options =result;
                }
            });
        }
    }

    function decodeVMTabForm(model, tabs){
        var result = {model:{},tabs:[]};
        var mdata = angular.fromJson(model);
        angular.extend(result.model,mdata);
        angular.forEach(tabs, function(tab){
            tab.form.model = vm.model;
            angular.forEach(tab.form.fields,function(field){
                if(field.key==""){
                    delete field.key;
                }
                if(angular.isDefined(field.extjson)&&field.extjson!=""){
                    var extObj = angular.fromJson(field.extjson);
                    angular.extend(field.templateOptions, extObj.templateOptions);
                    delete extObj.templateOptions;
                    for(var prop in extObj){
                        if(new RegExp("Expression").test(prop)){
                            //var obj = $scope.$eval(extObj[prop]);
                            //extObj[prop] = $scope.$eval(extObj[prop]);
                            if(extObj[prop]!=null){
                                if(new RegExp("function").test(extObj[prop])){
                                    var propValue = eval(extObj[prop]);
                                    extObj[prop] = propValue;
                                }else{
                                    //console.log(extObj[prop]);
                                    var obj = $scope.$eval(extObj[prop]);
                                    extObj[prop] = obj;
                                    //console.log(obj);
                                }
                            }
                        }else if(new RegExp("expressionProperties").test(prop)){
                            for(var p in extObj[prop]){
                                if(new RegExp("function").test(extObj[prop][p])){
                                    var propValue = eval(extObj[prop][p]);
                                    extObj[prop][p] = propValue;
                                }else{
                                    //if(p.indexOf("'")>=0){
                                    // var obj = $scope.$eval(extObj[prop][p]);
                                    // extObj[prop][$scope.$eval(p)]=obj;
                                    //}
                                }
                             }
                        }else if("watcher"==prop){
                            if(angular.isArray(extObj[prop])){
                                angular.forEach(extObj[prop],function(item,index){
                                    for(var p in item){
                                        if(new RegExp("function").test(item[p])){
                                            var propValue = eval(item[p]);
                                            extObj[prop][index][p] = propValue;
                                        }
                                    }
                                });
                            }else if(angular.isObject(extObj[prop])){
                                for(var p in extObj[prop]){
                                    if(new RegExp("function").test(extObj[prop][p])){
                                        var propValue = eval(extObj[prop][p]);
                                        extObj[prop][p] = propValue;
                                    }
                                }
                            }
                        }
                    }
                    angular.extend(field,extObj);
                    delete field.extjson;
                }

                if(field.extjson==""){
                    delete field.extjson;
                }
                if(angular.isDefined(field.templateOptions)){
                    var templateOs = field.templateOptions;
                    for(var property in templateOs){
                        //console.log(property);
                        if(angular.isString(templateOs[property])&& !(new RegExp("[\u4e00-\u9fa5]").test(templateOs[property]))){
                            if(new RegExp("function").test(templateOs[property])){
                                var propValue = eval(templateOs[property]);
                                field.templateOptions[property] = propValue;
                            }else{
                                if(that.has(templateOs[property])){
                                    field.templateOptions[property] = that.get(templateOs[property]);
                                }else{
                                    field.templateOptions[property] = templateOs[property];
                                }
                            }
                        }else if(templateOs[property]==null){
                            //delete field.templateOptions[property];
                        }else{
                        }
                    }
                }

                if(angular.isDefined(field.templateOptions) && angular.isDefined(field.templateOptions.extjson)){
                    var extObj = angular.fromJson(field.templateOptions.extjson);//JSON.parse(field.extjson);
                    angular.extend(field.templateOptions,extObj);
                    delete field.templateOptions.extjson;
                }
                //...
                if(field.templateOptions){
                    //处理远程获取数据控件方法调用
                    if(field.templateOptions.optionsUrl){
                        field.templateOptions.refresh = refreshSelectOptions;
                    }

                    //处理嵌套属性数据绑定/
                    if(field.templateOptions.pkey){
                        var pmodel,i= 0;
                        angular.forEach(field.templateOptions.pkey.split("."),function(p){
                            if(i==0){
                                if(result.model[p]==null){
                                    result.model[p] = {};
                                }
                                pmodel = result.model[p];
                                i++;
                            }else{
                                if(pmodel[p]==null){
                                    pmodel[p] = {};
                                }
                                pmodel = pmodel[p];
                            }
                        });
                        if(pmodel!=null){
                            field.model = pmodel;
                            if(pmodel[field.key]==null){
                                pmodel[field.key] = null;
                            }
                        }
                    }else{
                        if(result.model[field.key]==null){
                            result.model[field.key] = null;
                        }
                    }
                    //处理弹出框组件初始化
                    if(field.type=="ui-input-selectmodal"){
                        field.templateOptions.modal = $modal;
                        //field.templateOptions.Restangular = Restangular;
                    }else if(field.type=="ui-userselect"){
                        field.templateOptions.modal = $modal;
                        //field.templateOptions.Restangular = Restangular;
                    }else if(field.type=="ui-multiuserselect"){
                        field.templateOptions.modal = $modal;
                    }else if(field.type=="ui-modelselect"){
                        field.templateOptions.modal = $modal;
                        //field.templateOptions.Restangular = Restangular;
                    }else if(field.type=="ui-dropfile"){
                        field.templateOptions.fileUploader = new FileUploader({
                            url:'/uploader'
                        });
                        field.templateOptions.taskId = $stateParams.taskId;
                        field.templateOptions.processInstanceId = $stateParams.processInstanceId;
                        field.templateOptions.userId = $rootScope.user.id;
                        //field.ApiService=api_bpm_domain;
                    }else if(field.type=="ui-dropfiletable"){
                        if(field.templateOptions.processInstanceId){
                            
                        }else{
                            field.templateOptions.processInstanceId = $stateParams.processInstanceId;
                        }
                    }else if(field.type=="ui-repeatSection"){
                        var repeatForm = {
                            model:{

                            },
                            fields:field.templateOptions.fields
                        };
                        repeatForm.model[field.key]=[];
                        decodeVMTabForm(repeatForm);
                    }
                }
                // console.log(field);
                //field
                //result.fields.push(field);
            })
        });
        
        vm.originalTabs = angular.copy(vm.form);        
    }

    //解析自定义表单设计数据
    function decodeVMForm(vmForm){
        var result = {model:{},tabs:[]};
        //设置模型实体数据 begin
//        var mdata = vmForm.model;
        //解析数据实体
        var mdata = angular.fromJson(vmForm.model);//JSON.parse(field.extjson);
        angular.extend(result.model,mdata);
        //设置模型实体数据 end
        //解析设计数据生成表单项 begin
        var fields = [];
        //处理修改设计数据中展示设置
        angular.forEach(vmForm.tabs, function(field){
            if(field.key==""){
                delete field.key;
            }

            if(angular.isDefined(field.extjson)){
                var extObj = angular.fromJson(field.extjson);//JSON.parse(field.extjson);
                angular.extend(field.templateOptions, extObj.templateOptions);
                delete extObj.templateOptions;
                for(var prop in extObj){
                    if(new RegExp("Expression").test(prop)){
                        //var obj = $scope.$eval(extObj[prop]);
                        //extObj[prop] = $scope.$eval(extObj[prop]);
                        if(extObj[prop]!=null){
                            if(new RegExp("function").test(extObj[prop])){
                                var propValue = eval(extObj[prop]);
                                extObj[prop] = propValue;
                            }else{
                                //console.log(extObj[prop]);
                                var obj = $scope.$eval(extObj[prop]);
                                extObj[prop] = obj;
                                //console.log(obj);
                            }
                        }
                    }else if(new RegExp("expressionProperties").test(prop)){
                        for(var p in extObj[prop]){
                            if(new RegExp("function").test(extObj[prop][p])){
                                var propValue = eval(extObj[prop][p]);
                                extObj[prop][p] = propValue;
                            }else{
                                //if(p.indexOf("'")>=0){
                                // var obj = $scope.$eval(extObj[prop][p]);
                                // extObj[prop][$scope.$eval(p)]=obj;
                                //}
                            }
                         }
                    }else if("watcher"==prop){
                        if(angular.isArray(extObj[prop])){
                            angular.forEach(extObj[prop],function(item,index){
                                for(var p in item){
                                    if(new RegExp("function").test(item[p])){
                                        var propValue = eval(item[p]);
                                        extObj[prop][index][p] = propValue;
                                    }
                                }
                            });
                        }else if(angular.isObject(extObj[prop])){
                            for(var p in extObj[prop]){
                                if(new RegExp("function").test(extObj[prop][p])){
                                    var propValue = eval(extObj[prop][p]);
                                    extObj[prop][p] = propValue;
                                }
                            }
                        }
                    }
                }
                angular.extend(field,extObj);
                delete field.extjson;
            }


            if(angular.isDefined(field.templateOptions)){
                var templateOs = field.templateOptions;
                for(var property in templateOs){
                    //console.log(property);
                    if(angular.isString(templateOs[property])&& !(new RegExp("[\u4e00-\u9fa5]").test(templateOs[property]))){
                        if(new RegExp("function").test(templateOs[property])){
                            var propValue = eval(templateOs[property]);
                            field.templateOptions[property] = propValue;
                        }else{
                            if(that.has(templateOs[property])){
                                field.templateOptions[property] = that.get(templateOs[property]);
                            }else{
                                field.templateOptions[property] = templateOs[property];
                            }
                        }
                    }else if(templateOs[property]==null){
                        //delete field.templateOptions[property];
                    }else{
                    }
                }
            }
            console.log(field);
            if(angular.isDefined(field.templateOptions) && angular.isDefined(field.templateOptions.extjson)){
                var extObj = angular.fromJson(field.templateOptions.extjson);//JSON.parse(field.extjson);
                angular.extend(field.templateOptions,extObj);
                delete field.templateOptions.extjson;
            }
            //...
            if(field.templateOptions){
                //处理远程获取数据控件方法调用
                if(field.templateOptions.optionsUrl){
                    field.templateOptions.refresh = refreshSelectOptions;
                }

                //处理嵌套属性数据绑定/
                if(field.templateOptions.pkey){
                    var pmodel,i= 0;
                    angular.forEach(field.templateOptions.pkey.split("."),function(p){
                        if(i==0){
                            if(result.model[p]==null){
                                result.model[p] = {};
                            }
                            pmodel = result.model[p];
                            i++;
                        }else{
                            if(pmodel[p]==null){
                                pmodel[p] = {};
                            }
                            pmodel = pmodel[p];
                        }
                    });
                    if(pmodel!=null){
                        field.model = pmodel;
                        if(pmodel[field.key]==null){
                            pmodel[field.key] = null;
                        }
                    }
                }else{
                    if(result.model[field.key]==null){
                        result.model[field.key] = null;
                    }
                }
                //处理弹出框组件初始化
                if(field.type=="ui-input-selectmodal"){
                    field.templateOptions.modal = $modal;
                    //field.templateOptions.Restangular = Restangular;
                }else if(field.type=="ui-userselect"){
                    field.templateOptions.modal = $modal;
                    //field.templateOptions.Restangular = Restangular;
                }else if(field.type=="ui-multiuserselect"){
                    field.templateOptions.modal = $modal;
                }else if(field.type=="ui-modelselect"){
                    field.templateOptions.modal = $modal;
                    //field.templateOptions.Restangular = Restangular;
                }else if(field.type=="ui-dropfile"){
                    field.templateOptions.fileUploader = new FileUploader({
                        url:'/uploader'
                    });
                    field.templateOptions.taskId = $stateParams.taskId;
                    field.templateOptions.processInstanceId = $stateParams.processInstanceId;
                    field.templateOptions.userId = $rootScope.user.id;
                    //field.ApiService=api_bpm_domain;
                }else if(field.type=="ui-dropfiletable"){
                    if(field.templateOptions.processInstanceId){
                        
                    }else{
                        field.templateOptions.processInstanceId = $stateParams.processInstanceId;
                    }
                }else if(field.type=="ui-repeatSection"){
                    var repeatForm = {
                        model:{

                        },
                        fields:field.templateOptions.fields
                    };
                    repeatForm.model[field.key]=[];
                    decodeVMForm(repeatForm);
                }
            }

//          console.log(field);
            result.fields.push(field);
        });
        angular.extend($scope.vm.fields,result.fields);
        angular.extend($scope.vm.model,result.model);
        $scope.formData = vmForm;
        //console.log($scope.vm);

        //解析设计数据生成表单项 end
        return result;
    }
    //======================处理表单设计数据  结束========================
    $scope.ldloading = {};

    function filter(obj) {
        angular.forEach(obj, function(key, value){
            if (value === "" || value === null){
                delete obj[key];
            } else if (Object.prototype.toString.call(value) === '[object Object]') {
                filter(value);
            } else if (angular.isArray(value)) {
                angular.forEach(value,function(item){
                    filter(item);
                });
            }
        });
    }


    function invokeOnAllFormOptions(fn) {
      angular.forEach(vm.tabs, function(tab) {
        if (tab.form.options && tab.form.options[fn]) {
          tab.form.options[fn]();
        }
      });
    }

    function encodeCIData(data){
        /*
          create/update state:未审核
          create createtime:系统时间
          create/update lastupdatetime : 系统时间
          label:ci分类
         */
        if($scope.classify){
            var baseprop = ['uuid','name','type','label','status','createtime','lastupdatetime','props'];//state｜audittime//createtime//removeflag|removetime//configperson//lastupdateperson//manager//useradmin
            var extraprop = 'props';
            data[extraprop] = {};
            for(var key in data){
                console.log(data[key]);
                if(_.indexOf(baseprop, key)>=0){
                    continue;
                }else{
                    data[extraprop][key] = data[key];
                    delete data[key];
                }
            }
            if($rootScope.user){
                data[extraprop]['lastupdateperson']=$rootScope.user.name;
                data[extraprop]['configperson']=$rootScope.user.name;
                var isCMAdminFlag = false;
                angular.forEach($rootScope.user.role,function(roleItem){
                    if(roleItem.rolecode == "cmdb charge"){
                        isCMAdminFlag = true;
                    }
                })
                if(!isCMAdminFlag){
                    data[extraprop]['state']='1';
                }else{
                    // if(data[extraprop]['state']=='3'||data[extraprop]['state']=='4'){
                        data[extraprop]['audittime']=moment(new Date()).format('YYYY-MM-DD HH:mm:ss');
                    // }else{data[extraprop]['state']='1';}
                    // data[extraprop]['state']='1';
                }
            }
            data.label=$scope.classify;
            return data;
        }
        return undefined;
    }

    function decodeCIModel(data){
        var extraprop = 'props';
        if(data[extraprop]){
            for(var key in data[extraprop]){
                    data[key] = data[extraprop][key];
            }
            delete data[extraprop];
        }
        data['iscmadmin']=false;
        angular.forEach($rootScope.user.role,function(roleItem){
            if(roleItem.rolecode == "cmdb charge"){
                data['iscmadmin'] = true;
            }
        })
        return data;
    }

    vm.remove = function(data, style){
        $scope.ldloading[style.replace('-', '_')] = true;
        var cidata = {
            label:data.label,
            id:$scope.ciId,
            uuid:data.uuid,
            name:data.name,
            props:{}
        };
        if($scope.ciId){
            cidata.props['removeflag']=true;
            //cidata.props['removetime']=new Date();
            api_cmdb.put(cidata,$scope.ciId).then(function(response){
                if(response){
                    var resData = Restangular.stripRestangular(response);
                    SweetAlert.swal({
                        title: "保存成功!",
                        confirmButtonColor: "#007AFF"
                    },function(){
                        refreshData($scope.classify);
                        reinitTabForm($scope.classify);
                    });
                }else{
                    SweetAlert.swal({
                      title: "系统错误",
                      text: "系统错误，请稍后重试!",
                      type: "error",
                      confirmButtonColor: "#DD6B55"
                    });
                }
                $scope.ldloading[style.replace('-', '_')] = false;
            });
        }else{
            $timeout(function () {
                $scope.ldloading[style.replace('-', '_')] = false;
            }, 2000);
        }

    }

    function formValid(){
        angular.forEach(vm.tabs,function(item){
            //item.
        })
    }

    vm.submit = function(data, style){
        $scope.ldloading[style.replace('-', '_')] = true;

        console.log(vm.form.$$parentForm.$valid);
        if (vm.form.$$parentForm.$valid) {
            invokeOnAllFormOptions('updateInitialValue');
            //alert(JSON.stringify(vm.model), null, 2);
            //vm.options.updateInitialValue();
            //console.log(vm.model);
            var cidata = encodeCIData(vm.model);
            if(cidata){
                //var cidata = ;
                if($scope.ciId){
                    api_cmdb.put(cidata,$scope.ciId).then(function(response){
                        if(response){
                            var resData = Restangular.stripRestangular(response);
                            SweetAlert.swal({
                                title: "保存成功!",
                                confirmButtonColor: "#007AFF"
                            },function(){
                                refreshData($scope.classify);
                                reinitTabForm($scope.classify);
                            });
                        }else{
                            SweetAlert.swal({
                              title: "系统错误",
                              text: "系统错误，请稍后重试!",
                              type: "error",
                              confirmButtonColor: "#DD6B55"
                            });
                        }
                        $scope.ldloading[style.replace('-', '_')] = false;
                    });
                }else{
                    api_cmdb.create(cidata).then(function(response){
                        if(response){
                            var resData = Restangular.stripRestangular(response);
                            SweetAlert.swal({
                                title: "保存成功!",
                                confirmButtonColor: "#007AFF"
                            },function(){
                                refreshData($scope.classify);
                                reinitTabForm($scope.classify);
                            });
                            // if(resData.status){
                            //     resData
                            // }
                        }else{
                            SweetAlert.swal({
                              title: "系统错误",
                              text: "系统错误，请稍后重试!",
                              type: "error",
                              confirmButtonColor: "#DD6B55"
                            });
                        }
                        $scope.ldloading[style.replace('-', '_')] = false;
                    });     
                }

            }else{
                SweetAlert.swal({
                          title: "错误",
                          text: "错误，请选择配置项分类!",
                          type: "error",
                          confirmButtonColor: "#DD6B55"
                });
            }
            //alert(JSON.stringify(cidata), null, 2);
            $scope.ldloading[style.replace('-', '_')] = true;
            return;            

            
            var _ = window._;
            vm.model = (function filter(obj) {
                var filtered = _.pick(obj, function (v) { return angular.isDefined(v) && v !== null && (angular.isArray(v)?v.length>0:true) && (_.isPlainObject(v)?(!_.isEmpty(v)):true);  });
                return _.cloneDeep(filtered, function (v) { return v !== filtered && _.isPlainObject(v) ? filter(v) : undefined; });
            })(vm.model);


            if(pdKey!=""){
                if($scope.oprcode=="save"){//保存
                    api_bpm_domain.save(taskId, vm.model).then(function(response){
                        if(response){
                            var resData = Restangular.stripRestangular(response);
                            SweetAlert.swal({
                                title: "保存成功!",
                                confirmButtonColor: "#007AFF"
                            },function(){
                                $state.go($scope.formData.cancelUri);
                            });
                            // if(resData.status){
                            //     resData
                            // }
                        }else{
                            SweetAlert.swal({
                              title: "系统错误",
                              text: "系统错误，请稍后重试!",
                              type: "error",
                              confirmButtonColor: "#DD6B55"
                            });
                        }
                        $scope.ldloading[style.replace('-', '_')] = false;
                    });
                }else{
                    switch($scope.formData.url){
                    case "start" :
                        vm.model["initUser"]=$rootScope.user.id;
                        if(vm.model["assignee"]||vm.model["candidateGroups"]){

                        }else{
                            vm.model["assignee"]=$rootScope.user.id;
                        }                        
                        api_bpm_domain.start(pdKey,vm.model).then(function(response){
                            if(response){
                                var resData = Restangular.stripRestangular(response);
                                SweetAlert.swal({
                                    title: "提交成功!",
                                    confirmButtonColor: "#007AFF"
                                },function(){
                                    $state.go($scope.formData.cancelUrl);
                                });
                            }else{
                                SweetAlert.swal({
                                  title: "系统错误",
                                  text: "系统错误，请稍后重试!",
                                  type: "error",
                                  confirmButtonColor: "#DD6B55"
                                });
                            }
                            $scope.ldloading[style.replace('-', '_')] = false;
                        });
                        break;
                    case "complete" :
    //                    api_bpm_domain.complete(pdKey, userId, vm.model).then(function(response){
                        console.log("complete taskId::"+$stateParams.taskId);
                        api_bpm_domain.complete($stateParams.taskId, userId, vm.model).then(function(response){
                            if(response){
                                var resData = Restangular.stripRestangular(response);
                                SweetAlert.swal({
                                    title: "提交成功!",
                                    confirmButtonColor: "#007AFF"
                                },function(){
                                    // if($scope.uploader.getNotUploadedItems().length>0&&response.data.processInstanceId){
                                    //     // $scope.uploader.options.url();
                                    //     $scope.uploader.onBeforeUploadItem = function(item) {
                                    //         item.url = api_bpm_domain.saveAttachments($stateParams.processInstanceId,$stateParams.taskId,$scope.user.id).getRequestedUrl();
                                    //         console.info('onBeforeUploadItem', item);
                                    //     };
                                    //     $scope.uploader.uploadAll();
                                    // }
                                    $state.go($scope.formData.cancelUrl);
                                });
                            }else{
                                SweetAlert.swal({
                                  title: "系统错误",
                                  text: "系统错误，请稍后重试!",
                                  type: "error",
                                  confirmButtonColor: "#DD6B55"
                                });
                            }
                            $scope.ldloading[style.replace('-', '_')] = false;
                        });
                        break;
                    default:
                        $scope.ldloading[style.replace('-', '_')] = false;
                        break;
                    }
                }
                // var submitFunc = api_bpm_domain[$scope.formData.url]
                // if(anuglar.isFunction(submitFunc)){
                //     submitFunc.apply(null, pdKey)
                // }
            }
        }else{
            if(vm.form.$$parentForm.$error){
                SweetAlert.swal({
                  title: "校验错误",
                  text: "请填写必填项!",
                  type: "error",
                  confirmButtonColor: "#DD6B55"
                });
                angular.forEach(vm.form.$$parentForm.$error.required, function(item){
                    angular.forEach(vm.tabs,function(tab){
                        angular.forEach(tab.form.fields,function(f){
                            if(f.name == item.$name){
                                f.validation.show = true;
                                tab.active=true;
                            }
                        })
                    })
                });
                $scope.ldloading[style.replace('-', '_')] = false;
            }
        }
    };

    $scope.vm = vm;


    //cmdb list
    $scope.gridOptions = {};
    $scope.gridOptions.data = 'myData';
    $scope.gridOptions.enableColumnResizing = true;
    $scope.gridOptions.enableFiltering = true;
    $scope.gridOptions.enableGridMenu = true;
    $scope.gridOptions.enableRowSelection = true;
    $scope.gridOptions.enableRowHeaderSelection=false;
    $scope.gridOptions.showGridFooter = true;
    $scope.gridOptions.showColumnFooter = true;
    $scope.gridOptions.fastWatch = true;
    $scope.gridOptions.useExternalPagination = false;
    $scope.gridOptions.paginationPageSizes = [10];
    $scope.gridOptions.paginationPageSize = 10;
    $scope.gridOptions.multiSelect = false;
    $scope.gridOptions.modifierKeysToMultiSelect = false;
    //$scope.gridOptions.noUnselect = true;

    //$scope.gridOptions.rowTemplate = "<div ng-dblclick=\"grid.appScope.pdList.onDblClick(row)\" ng-repeat=\"(colRenderIndex, col) in colContainer.renderedColumns track by col.uid\" ui-grid-one-bind-id-grid=\"rowRenderIndex + '-' + col.uid + '-cell'\" class=\"ui-grid-cell\" ng-class=\"{ 'ui-grid-row-header-cell': col.isRowHeader }\" role=\"{{col.isRowHeader ? 'rowheader' : 'gridcell'}}\" ui-grid-cell></div>";
    //
    $scope.gridOptions.rowIdentity = function(row) {
        return row.id;
    };
    $scope.gridOptions.getRowIdentity = function(row) {
        return row.id;
    };
    $scope.transferstate = function(state){
    	    if(state=="1"){return state="未审核"}
    	    else if(state=="2"){return state="已审核"}
    	    else if(state=="3"){return state="不匹配"}
    	    else if(state=="4"){return state="丢失"}
   }
   $scope.transferremoveflag = function(removeflag){
    	    if(removeflag==true){return removeflag="已删除"}
    	    else if(removeflag==false){return removeflag="正常"}
   }
    $scope.gridOptions.columnDefs = [
    {
        name: 'uuid',
        displayName: '搜索代码',
        width: 100
    }, {
        name: 'name',
        displayName: '配置项名称',
        width: 100
    },{
        name: 'status',
        displayName: '配置项状态',
        width: 140
    }, {
        name: 'props.state',
        displayName: '配置项审批状态',
        width: 100,
         cellTemplate:'<div class="ui-grid-cell-contents">{{grid.appScope.transferstate(row.entity.props.state)}}</div>'
    }, {
    	name: 'props.configperson',
        displayName: '配置项管理员',
        width: 100
    }, {
        name: 'props.removeflag',
        displayName: '是否删除',
        width: 140,
        cellTemplate:'<div class="ui-grid-cell-contents">{{grid.appScope.transferremoveflag(row.entity.props.removeflag)}}</div>'
    }];
    $scope.gridOptions.onRegisterApi = function(gridApi) {
        $scope.gridApi = gridApi;
        /*
        // gridApi.pagination.on.paginationChanged($scope, function(newPage, pageSize) {
        //     console.log(newPage);
        //     console.log(pageSize);
        //     refreshData({
        //         "idx": newPage - 1,
        //         "sum": pageSize
        //     });
        // });
		*/
        gridApi.selection.on.rowSelectionChanged($scope, function(data) {
            //$scope.selected.item = data.entity;
            $scope.entity = angular.copy(data.entity);
            $scope.ciId = data.entity.id;
            //TODO
            vm.model=$scope.vm.model=decodeCIModel($scope.entity);
            angular.forEach($scope.vm.tabs, function(tab){
                tab.form.model = vm.model;
            });
            //decodeVMTabForm($scope.entity, vm.tabs);
            //console.log(data);
        });
    };
    // $scope.gridOptions.appScopeProvider = { 
    //         onDblClick : function(row) {
    //             $state.go('app.form.detail',{data:row, formKey:'changeDetail', pdKey:'change'});
    //             //var url = '//google.com';
    //             //$window.open(url, "_blank", "height=600,width=800,toolbar=no,location=no,menubar=no,titlebar=no");
    //         }
    // };

    this.selectRowFunction = function(data) {
        $scope.ciId = data.id;
        console.log(data);
        //    $state.go('app.process.modeler',{modelId:data.id});
        // $state.go('app.change.editor', {
        //     taskId: data.taskId,
        //     processInstanceId: data.processInstanceId
        // });
    };

    var reinitTabForm = function(classify){
        $scope.ciId = undefined;
        api_configure_form.renderTabForm(classify).then(function(data){
            var myData = Restangular.stripRestangular(data);
            //angular.extend($scope.vm.fields,result.fields);
            //angular.extend($scope.vm.model,result.model);
            $scope.templateProps = myData;
            $scope.vm.tabs = myData;
            vm.model = {};
            decodeVMTabForm(vm.model, vm.tabs);
            //$scope.vm.originalTabs = angular.copy($scope.vm.form);
            //console.log(myData);
        });
    }

    var refreshData = function(filterData){
        if(angular.isUndefined(filterData)){
          return;
        }
        $scope.myData = [];
        api_cmdb.query({'sign':filterData}).then(function(data){
            var myData = Restangular.stripRestangular(data);
            console.log(myData.data);
            if(myData.data&&myData.status==200){
                var ret = myData.data.node;
                // for(var i=0;i<ret.length;i++){
                //     if(ret[i].status){
                //     	if(ret[i].status=="1"){ ret[i].statu="已部署"}
                //     	else if(ret[i].status=="2"){ ret[i].statu="测试中"}
                //         else if(ret[i].status=="3"){ ret[i].statu="使用中"}
                //         else if(ret[i].status=="4"){ ret[i].statu="维护中"}
                //         else if(ret[i].status=="5"){ ret[i].statu="报废"}
                //         else if(ret[i].status=="6"){ ret[i].statu="备用"}
                //     }
                // }
                $scope.gridOptions.totalItems = ret.length;
                $scope.myData = ret;
            }            
        });
    };

	var apple_selected, tree, treedata_avm, treedata_geography;
    $scope.my_tree_handler = function (branch) {
        //var _ref;
        $scope.ciclassify=branch;
        $scope.classify=branch.prefix.toLowerCase()+branch.sign;
        refreshData($scope.classify);
        $scope.ciId = undefined;
        api_configure_form.renderTabForm($scope.classify).then(function(data){
            var myData = Restangular.stripRestangular(data);
            //angular.extend($scope.vm.fields,result.fields);
            //angular.extend($scope.vm.model,result.model);
            $scope.templateProps = myData;
            $scope.vm.tabs = myData;
            vm.model = {};
            vm.model["loginUser"]= $rootScope.user.name;
            console.log(vm.model);
            decodeVMTabForm(vm.model, vm.tabs);
            //$scope.vm.originalTabs = angular.copy($scope.vm.form);
            console.log(myData);
        });
        console.log(branch);
    };
    $scope.my_data = [];


    function convertListToTree(data, treeMap){
        var idToNodeMap = {}; //Keeps track of nodes using id as key, for fast lookup
        var root = null; //Initially set our loop to null
        var parentNode = null;
        //loop over data
        for(var i = 0; i < data.length; i++) {
            var datum = data[i];
            //each node will have children, so let's give it a "children" poperty
            datum.children = [];

            //add an entry for this node to the map so that any future children can
            //lookup the parent
            idToNodeMap[datum.id] = datum;

            //Does this node have a parent?
            if(typeof datum.parent === "undefined" || datum.parent == null) {
                //Doesn't look like it, so this node is the root of the tree
                root = datum;
                treeMap[datum.id] = root;
            } else {        
                //This node has a parent, so let's look it up using the id
                parentNode = idToNodeMap[datum.parent.id];

                //We don't need this property, so let's delete it.
                delete datum.parent;

                //Let's add the current node as a child of the parent node.
                parentNode.children.push(datum);        
            }
        }
        return root;
    }

    function convertParentToChildList(data){
        var treeMap = {};
        var list=[];
        convertListToTree(data, treeMap);
        angular.forEach(treeMap,function(item){
            list.push(item);
        });
        return list;
    }


    $scope.my_tree = tree = {};
    $scope.try_async_load = function () {
        $scope.my_data = [];
        $scope.doing_async = true;
        api_configure_data.fetchDataList('ciclassify',{'idx':0,'sum':100}).then(function(result){
            console.log(result['list']);
            $scope.my_data = convertParentToChildList(result['list']);
            $scope.doing_async = false;
            tree.expand_all();
            //console.log(treelist);
        });
    };

    $scope.try_async_load();

    var importUploader = $scope.importUploader = new FileUploader({
        url:api_cmdb.import().getRequestedUrl()
    });

    importUploader.filters.push({
        name: 'customFilter',
        fn: function(item /*{File|FileLikeObject}*/ , options) {
            var type = item.name.slice(item.name.lastIndexOf('.') + 1);
            //var type = '|' + item.type.slice(item.type.lastIndexOf('/') + 1) + '|';
            return (type == 'csv');
        }
    });
    importUploader.onWhenAddingFileFailed = function(item /*{File|FileLikeObject}*/ , filter, options) {
        console.info('onWhenAddingFileFailed', item, filter, options);
    };
    importUploader.onAfterAddingFile = function(fileItem) {
        console.info('onAfterAddingFile', fileItem);
    };
    importUploader.onAfterAddingAll = function(addedFileItems) {
        console.info('onAfterAddingAll', addedFileItems);
    };
    
    importUploader.onProgressItem = function(fileItem, progress) {
        console.info('onProgressItem', fileItem, progress);
    };
    importUploader.onProgressAll = function(progress) {
        console.info('onProgressAll', progress);
    };
    importUploader.onSuccessItem = function(fileItem, response, status, headers) {
        SweetAlert.swal({
            title: "导入成功!",
            confirmButtonColor: "#007AFF",
            type: "success"
        },function(){
                        refreshData($scope.classify);
        });
        console.info('onSuccessItem', fileItem, response, status, headers);

    };
    importUploader.onErrorItem = function(fileItem, response, status, headers) {
        console.info('onErrorItem', fileItem, response, status, headers);
        SweetAlert.swal({
                        title: "系统错误!",
                        text: "系统错误，请稍候重试!",
                        type: "error"
                    });
    };
    importUploader.onCancelItem = function(fileItem, response, status, headers) {
        console.info('onCancelItem', fileItem, response, status, headers);
    };
    importUploader.onCompleteItem = function(fileItem, response, status, headers) {
        console.info('onCompleteItem', fileItem, response, status, headers);
    };
    importUploader.onCompleteAll = function() {
        console.info('onCompleteAll');
    };

    $scope.ldloading = {};
    $scope.import = function(){
        $scope.ldloading.expand = true;
    	if(angular.isDefined($scope.ciclassify)&&$scope.ciclassify!=null){
    		if(angular.isUndefined($scope.ciclassify.children)||$scope.ciclassify.children.length==0){
    			importUploader.onBeforeUploadItem = function(item) {
			    	item.formData.push({'fileName':$scope.classify});
			    	item.formData.push({'uid':$rootScope.user.name});
			        console.info('onBeforeUploadItem', item);
			    };

    			importUploader.uploadAll();
                $scope.ldloading.expand = false;
    		}else{
    			SweetAlert.swal({
                        title: "参数不合法!",
                        text: "参数不合法，请选择没有子类的配置项导入!",
                        type: "error"
                    });
    		}
    	}else{
    		SweetAlert.swal({
                title: "参数不合法!",
                text: "参数不合法，请选择需要导入配置项分类!",
                type: "error"
            });
    	}      
    }
    $scope.ldloading = {};
    $scope.export = function(){
        $scope.ldloading.expand_right = true;
    	if(angular.isDefined($scope.ciclassify)&&$scope.ciclassify!=null){
    		if(angular.isUndefined($scope.ciclassify.children)||$scope.ciclassify.children.length==0){
    			api_cmdb.export($scope.classify).then(function(response){
    				var dataList = Restangular.stripRestangular(response);
    				if(dataList&&(dataList.length>=1)){
	    				var headers = [];
		    			var fieldHeaders = [];
		    			var fields = [];
		    			var rowData = [];

		    			if($scope.templateProps.length>0){
			    			angular.forEach($scope.templateProps, function(prop){
			    				headers.push(prop.title);
			    				angular.forEach(prop.form.fields, function(field, index){
			    					fieldHeaders.push(field.templateOptions.label);
			    					fields.push(field.key);
			    					if(index!=0){
			    						headers.push("");
			    					}	    					
			    				});				
			    			})
			    		}
			    		var rowLine = [];
			    		angular.forEach(dataList, function(data){
			    			rowLine = [];
			    			angular.forEach(fields,function(keyfield){
			    				if(data[keyfield]){
                                    if(keyfield=="state"){
                                        if(data[keyfield]=="1"){data[keyfield]="未审核"}
                                        else if(data[keyfield]=="2"){data[keyfield]="已审核"}
                                        else if(data[keyfield]=="3"){data[keyfield]="不匹配"}
                                        else if(data[keyfield]=="4"){data[keyfield]="丢失"}
                                        rowLine.push(data[keyfield]);
                                    }else if(keyfield=="removeflag"){
                                        if(data[keyfield]){data[keyfield]="已删除"}
                                        else{data[keyfield]="正常"}
			    					    rowLine.push(data[keyfield]);
                                    }else if(keyfield=="ownershipType"||keyfield=="bladeownershipType"||keyfield=="miniwnershipType"||keyfield=="bdcOwnershipType"){
                                        if(data[keyfield]=="1"){data[keyfield]="独立采购"}
                                        else if(data[keyfield]=="2"){data[keyfield]="项目采购"}
                                        else if(data[keyfield]=="3"){data[keyfield]="借用"}
                                        else if(data[keyfield]=="4"){data[keyfield]="赠送"}
                                        rowLine.push(data[keyfield]);
                                    }else if(keyfield=="createtime"||keyfield=="audittime"||keyfield=="lastupdatetime"||keyfield=="removetime"){
                                        data[keyfield]=moment(data[keyfield]).format('YYYY-MM-DD HH:mm:ss')
                                        rowLine.push(data[keyfield]);
                                    }else{
                                        if(data[keyfield]==true){data[keyfield]="是"}
                                        else if(data[keyfield]==false){data[keyfield]="否"}
                                        rowLine.push(data[keyfield]);
                                    // data[keyfield]=moment(data[keyfield]).format('YYYY-MM-DD HH:mm:ss')
                                    }
			    				}else{
			    					rowLine.push("");
			    				}
			    			})
			    			rowData.push(rowLine);
    					})
			    		
			    		var csvdata = headers.join(',') + '\r\n';
		    			csvdata = csvdata + fieldHeaders.join(',') + '\r\n';
		    			csvdata = csvdata + fields.join(',') + '\r\n';
		    			angular.forEach(rowData, function(line){
		    				csvdata = csvdata + line.join(',') + '\r\n';
		    			})
		    			csvdata = "\ufeff" + csvdata;
			    		
			    		var file = new Blob([ csvdata ], {
			                type : 'application/csv;charset=utf-8'
			            });
			            var filename = $scope.ciclassify.label;
			            var fileURL = URL.createObjectURL(file);
			            var a         = document.createElement('a');
			            a.href        = fileURL; 
			            a.target      = '_blank';
			            a.download    = filename +'.csv';
			            document.body.appendChild(a);
			            a.click();
                        $scope.ldloading.expand_right = false;
			    	}
    			})
    		}else{
	    		SweetAlert.swal({
                        title: "参数不合法!",
                        text: "参数不合法，请选择没有子类的配置项导出!",
                        type: "error"
                    });
	    	}
    	}else{
    		SweetAlert.swal({
                title: "参数不合法!",
                text: "参数不合法，请选择需要导出的配置项分类!",
                type: "error"
            });
    	}
    }

    $scope.download = function(){
    	if(angular.isDefined($scope.ciclassify)&&$scope.ciclassify!=null){
    		//api_cmdb.download($scope.sign).getRequestedUrl();
    		if(angular.isUndefined($scope.ciclassify.children)||$scope.ciclassify.children.length==0){
    			var filename = $scope.ciclassify.label;

	    		//$scope.ciclassify.
	    		var headers = [];
	    		var fieldHeaders = [];
	    		var fields = [];
	    		if($scope.templateProps.length>0){
	    			angular.forEach($scope.templateProps, function(prop){
	    				headers.push(prop.title);
	    				angular.forEach(prop.form.fields, function(field, index){
	    					fieldHeaders.push(field.templateOptions.label);
	    					fields.push(field.key);
	    					if(index!=0){
	    						headers.push("");
	    					}	    					
	    				}); 				
	    			})
	    		}

	    		if(headers.length>1){
	    			var csvdata = headers.join(',') + '\r\n';
	    			csvdata = csvdata + fieldHeaders.join(',') + '\r\n';
	    			csvdata = csvdata + fields.join(',') + '\r\n';
	    			csvdata = "\ufeff" + csvdata;
	    			var file = new Blob([ csvdata ], {
		                type : 'application/csv;charset=utf-8'
		                //type : 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'
		            });
		            //trick to download store a file having its URL
		            var fileURL = URL.createObjectURL(file);
		            var a         = document.createElement('a');
		            a.href        = fileURL; 
		            a.target      = '_blank';
		            a.download    = filename +'.csv';
		            document.body.appendChild(a);
		            a.click();
	    		}
	    	}else{
	    		SweetAlert.swal({
                        title: "参数不合法!",
                        text: "参数不合法，请选择没有子类的配置项进行模版下载!",
                        type: "error"
                    });
	    	}
    	}else{
    		SweetAlert.swal({
                title: "参数不合法!",
                text: "参数不合法，请选择需要下载模版的配置项分类!",
                type: "error"
            });
    	}
    }
}]);